package com.b.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.b.dao.VideoMapper;
import com.b.domain.Category;
import com.b.domain.Video;
import com.b.repository.CategoryRepository;
import com.b.repository.VideoRepository;
import com.b.service.VideoService;
import com.b.vo.Result;

import jakarta.annotation.Resource;

@Service
public class VideoServiceImpl implements VideoService {

    @Resource
    private VideoMapper videoMapper;
    @Resource
    private VideoRepository videoRepository;
    @Resource
    private CategoryRepository categoryRepository;

    @Override
    public boolean deleteByPrimaryKey(Integer id) {
        return videoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Video record) {
        return videoMapper.insert(record);
    }

    @Override
    public int insertSelective(Video record) {
        return videoMapper.insertSelective(record);
    }

    @Override
    public Video selectByPrimaryKey(Integer id) {
        return videoMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Video record) {
        return videoMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Video record) {
        return videoMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Video> getAll() {
        return videoMapper.getAll();
    }


    @Override
    public List<Video> list() {
        // 从ES中获取所有视频数据
        Iterable<Video> videoIterable = videoRepository.findAll();
        List<Video> videoList = StreamSupport.stream(videoIterable.spliterator(), false)
                .collect(Collectors.toList());

        // 提取所有视频的categoryId
        List<Integer> categoryIds = videoList.stream()
                .map(Video::getCategoryId)
                .filter(id -> id != null)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询categoryType
        Iterable<Category> categories = categoryRepository.findAllById(categoryIds);
        List<Category> categoryList = StreamSupport.stream(categories.spliterator(), false).collect(Collectors.toList());
        // 构建categoryId到categoryType的映射
        Map<Integer, String> categoryMap = categoryList.stream()
                .collect(Collectors.toMap(Category::getId, Category::getType));

        // 填充每个视频的categoryType
        videoList.forEach(video -> {
            Integer categoryId = video.getCategoryId();
            if (categoryId != null) {
                video.setCategoryType(categoryMap.get(categoryId));
            }
        });

        return videoList;
    }


    @Override
    @Transactional
    public Result audit(Integer id, String result, String reason) {
        try {
            // 参数校验
            if (id == null) {
                return new Result().setCode("400").setMsg("ID 不能为空");
            }

            // 先修改数据库
            Video video = videoRepository.findById(id).orElse(null);
            if (video != null) {
                videoMapper.audit(id, result, reason);
                video.setResult(result);
                video.setReason(reason);
                videoRepository.save(video);
            }
            return new Result().setCode("200").setMsg("操作成功");

        } catch (Exception e) {
            e.printStackTrace();
            return new Result().setCode("500").setMsg("服务器异常");
        }
    }

    @Override
    @Transactional
    public Result delete(Integer id) {
        try {
            boolean b = videoMapper.deleteByPrimaryKey(id);
            if (b) {
                videoRepository.deleteById(id);
                return new Result().setCode("200").setMsg("删除成功");
            } else {
                return new Result().setCode("400").setMsg("删除失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new Result().setCode("500").setMsg("服务器异常");
        }
    }
    @Override
    public SearchPage<Video> getByCategoryId(Integer categoryId, PageRequest pageRequest) {
        // 通过categoryId和result not in过滤，直接从ES分页查询
        java.util.List<String> excludeResults = java.util.Arrays.asList("reject", null, "");
        SearchPage<Video> videoPage = videoRepository.findByCategoryIdAndResultNotIn(categoryId, excludeResults, pageRequest);

        // 提取所有视频实体
        List<Video> videoList = videoPage.getContent().stream()
                .map(org.springframework.data.elasticsearch.core.SearchHit::getContent)
                .collect(Collectors.toList());

        // 提取所有视频的categoryId
        List<Integer> categoryIds = videoList.stream()
                .map(Video::getCategoryId)
                .filter(java.util.Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询categoryType
        Iterable<Category> categories = categoryRepository.findAllById(categoryIds);
        List<Category> categoryList = StreamSupport.stream(categories.spliterator(), false).collect(Collectors.toList());

        // 构建categoryId到categoryType的映射
        Map<Integer, String> categoryMap = categoryList.stream()
                .collect(Collectors.toMap(Category::getId, Category::getType));

        // 填充每个视频的categoryType
        videoList.forEach(video -> {
            Integer videoCategoryId = video.getCategoryId();
            if (videoCategoryId != null) {
                video.setCategoryType(categoryMap.get(videoCategoryId));
            }
        });

        // 回写到SearchHit
        for (int i = 0; i < videoPage.getContent().size(); i++) {
            videoPage.getContent().get(i).getContent().setCategoryType(videoList.get(i).getCategoryType());
        }

        return videoPage;
    }

    @Override
    @Transactional
    public Result update(Integer videoId, Integer categoryId) {
        try {
            // 先从数据库中查询视频信息
            Video video = videoMapper.selectByPrimaryKey(videoId);
            if (video != null) {
                // 更新数据库中的分类ID
                video.setCategoryId(categoryId);
                videoMapper.updateByPrimaryKeySelective(video);

                // 同步更新ES中的数据
                Video esVideo = videoRepository.findById(videoId).orElse(null);
                if (esVideo != null) {
                    esVideo.setCategoryId(categoryId);
                    videoRepository.save(esVideo);
                }

                return new Result().setCode("200").setMsg("修改成功");
            } else {
                return new Result().setCode("404").setMsg("视频不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result().setCode("500").setMsg("服务器异常");
        }
    }

    @Override
    public List<Video> list2() {
        // 从ES中获取所有视频数据
        Iterable<Video> videoIterable = videoRepository.findAll();
        List<Video> videoList = StreamSupport.stream(videoIterable.spliterator(), false)
                .filter(video -> "pass".equals(video.getResult()))
                .collect(Collectors.toList());

        // 提取所有视频的categoryId
        List<Integer> categoryIds = videoList.stream()
                .map(Video::getCategoryId)
                .filter(id -> id != null)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询categoryType
        Iterable<Category> categories = categoryRepository.findAllById(categoryIds);
        List<Category> categoryList = StreamSupport.stream(categories.spliterator(), false).collect(Collectors.toList());
        // 构建categoryId到categoryType的映射
        Map<Integer, String> categoryMap = categoryList.stream()
                .collect(Collectors.toMap(Category::getId, Category::getType));

        // 填充每个视频的categoryType
        videoList.forEach(video -> {
            Integer categoryId = video.getCategoryId();
            if (categoryId != null) {
                video.setCategoryType(categoryMap.get(categoryId));
            }
        });

        return videoList;
    }
}
